<template>
  <div class="carbon-credits-management">
    <div class="sidebar">
      <a-menu mode="inline">
        <a-menu-item key="viewProjects">查看所有项目</a-menu-item>
        <a-menu-item key="userManagement">用户管理</a-menu-item>
        <a-menu-item key="auditLogs">日志审计</a-menu-item>
        <a-menu-item key="help">帮助</a-menu-item>
      </a-menu>
    </div>

    <div class="main-content">
      <a-card title="项目列表" class="card">
        <a-button type="primary" style="margin-bottom: 16px" @click="showAddProjectModal">新增项目</a-button>
        <a-table
          :dataSource="projects"
          :columns="projectColumns"
          rowKey="id"
          bordered
          @change="handleChange"
          class="carbon-assets-table"
          :pagination="pagination"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'action'">
              <span class="action-buttons">
                <a @click="editCarbonAsset(record)" class="edit-button">编辑</a>
                <a-divider type="vertical" />
                <a @click="deleteCarbonAsset(record)" class="delete-button">删除</a>
              </span>
            </template>
          </template>
        </a-table>
      </a-card>

      <a-modal v-model:open="isModalVisible" title="新增碳信用项目" @ok="submitProject" @cancel="closeModal">
        <a-form layout="vertical">
          <a-form-item label="项目名称">
            <a-input v-model:value="newProject.projectName" placeholder="输入项目名称" />
          </a-form-item>
          <a-form-item label="碳资产类型">
            <a-select
              v-model:value="newProject.assetCategoryId"
              style="width: 100%"
              :fieldNames="{ label: 'caCategoryName', value: 'caCategoryId' }"
              placeholder="选择碳资产类型"
              :options="assetsCategories"
            ></a-select>
          </a-form-item>
          <a-form-item label="减排量">
            <a-input v-model:value="newProject.reductionAmount" placeholder="输入减排量" />
          </a-form-item>
          <a-form-item label="认证状态">
            <a-select v-model:value="newProject.certificationStatus">
              <a-select-option value="已认证">已认证</a-select-option>
              <a-select-option value="待认证">待认证</a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="详细描述">
            <a-textarea v-model:value="newProject.description" placeholder="输入详细描述" />
          </a-form-item>
        </a-form>
      </a-modal>
    </div>
  </div>
</template>

<script setup>
  //  import { AppstoreOutlined, MailOutlined } from '@ant-design/icons-vue';
  import { h, reactive, computed, ref, onMounted } from 'vue';
  import { carbonCredit } from '/@/api/Carbon module/Carbon asset module/Carbon asset project/carbonCredit';
  import { smartSentry } from '/@/lib/smart-sentry';

  // 初始化状态和数据
  const state = reactive({
    selectedKeys: [],
  });
  const projects = ref([]);
  const isModalVisible = ref(false);
  const newProject = reactive({
    projectName: '',
    assetCategoryId: '',
    reductionAmount: '',
    certificationStatus: '',
    description: '',
  });

  // 项目列配置
  const projectColumns = [
    { title: '项目名称', dataIndex: 'projectName', key: 'projectName' },
    { title: '碳资产类型', dataIndex: 'caCategoryName', key: 'caCategoryName' },
    { title: '减排量', dataIndex: 'reductionAmount', key: 'reductionAmount' },
    { title: '认证状态', dataIndex: 'certificationStatus', key: 'certificationStatus' },
    { title: '操作', dataIndex: 'action', key: 'action' },
  ];

  // 事件处理函数
  const showAddProjectModal = () => {
    newProject.projectName = '';
    newProject.assetCategoryId = '';
    newProject.reductionAmount = '';
    newProject.certificationStatus = '';
    newProject.description = '';
    isEdit.value = false;
    isModalVisible.value = true;
  };

  const submitProject = async () => {
    if (newProject.projectName && newProject.assetCategoryId && newProject.reductionAmount) {
      if (isEdit.value) {
        // 如果项目存在，则更新该项目
        try {
          await carbonCredit.Update({ ...newProject });
          queryData();
        } catch (error) {
          console.log(error);
        }
      } else {
        // 添加新项目
        try {
          await carbonCredit.Add({ ...newProject });
          queryData();
        } catch (error) {
          console.log(error);
        }
      }
      closeModal();
    } else {
      // 在此处处理表单验证失败的情况
      console.log('请填写所有必需的字段。');
    }
  };

  const closeModal = () => {
    isModalVisible.value = false;
  };

  const isEdit = ref(false);
  const editCarbonAsset = (record) => {
    isEdit.value = true;
    // 将选择的项目数据填入新的项目对象中
    newProject.certifiedProjectId = record.certifiedProjectId;
    newProject.projectName = record.projectName;
    assetsCategories.value.forEach((item) => {
      if (item.caCategoryName == record.caCategoryName) {
        newProject.assetCategoryId = item.caCategoryId;
      }
    });
    newProject.reductionAmount = record.reductionAmount;
    newProject.certificationStatus = record.certificationStatus;
    newProject.description = record.description || ''; // 如果没有描述，确保是空字符串

    // 显示模态框
    isModalVisible.value = true;
  };

  const deleteCarbonAsset = async (record) => {
    try {
      await carbonCredit.Delete(record.certifiedProjectId);
      queryData();
    } catch (error) {
      console.log(error);
    }
  };

  // 查询碳信用列表
  const pagination = computed(() => ({
    total: total.value,
    pageSize: queryFormState.pageSize,
    current: queryFormState.pageNum,
    showTotal: (total) => `总共${total}项`,
  }));
  const queryFormState = reactive({
    pageNum: 1,
    pageSize: 10,
  });
  const tableLoading = ref(false);
  const total = ref(0); //总数
  const queryForm = reactive({ ...queryFormState });
  async function queryData() {
    tableLoading.value = true;
    try {
      queryForm.pageNum = queryFormState.pageNum; // 确保页码同步
      queryForm.pageSize = queryFormState.pageSize;
      let queryResult = await carbonCredit.query(queryForm);
      projects.value = queryResult.data.list;
      total.value = queryResult.data.total;
    } catch (e) {
      smartSentry.captureError(e);
    } finally {
      tableLoading.value = false;
    }
  }
  const handleChange = (pagination, filters, sorter) => {
    queryFormState.pageNum = pagination.current; // 更新当前页
    queryFormState.pageSize = pagination.pageSize; // 更新页大小
    queryData();
  };

  // 碳资产类型
  const assetsCategories = ref([]);
  async function queryAssetsCategory() {
    let queryResult = await carbonCredit.queryAssetsCategory({
      pageNum: 1,
      pageSize: 100,
    });
    assetsCategories.value = queryResult.data.list;
  }

  onMounted(() => {
    queryData();
    queryAssetsCategory();
  });
</script>

<style scoped>
  .carbon-credits-management {
    display: table;
    width: 100%;
  }

  .sidebar {
    width: 240px;
    background-color: white; /* 侧边栏背景色 */
    color: white;
    display: flex;
    flex-direction: column;
    display: table-cell;
    box-shadow: 2px 0 5px rgba(0, 0, 0, 0.1);
  }

  .main-content {
    flex-grow: 1;
    padding-left: 10px;
    display: table-cell;
  }
  .main-card {
    border-radius: 8px;
  }
  .card {
    background-color: white;
    border-radius: 8px;
    /* box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1); */
  }
  .ant-input {
    width: 100%;
  }

  .action-buttons {
    display: flex;
    align-items: center;
  }

  .ant-button {
    margin-top: 8px;
  }

  .ant-button + .ant-button {
    margin-left: 8px;
  }
</style>
